package com.erdos.common.util;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public final class BeanHelper {
private static BeanHelper singleton;
    
    private ApplicationContext appContext;
    private ServletContext servletContext;
    
    private BeanHelper() {}
    
    public static void setServletContext(ServletContext servletContext)
    {

        if(singleton == null)
        {
            singleton = new BeanHelper();
        }

        singleton.servletContext = servletContext;

     }
    
    public static Object getBean(String beanName)
    {
        if(singleton == null)
        {
            singleton = new BeanHelper();
        }
        
        if(singleton.appContext == null && singleton.servletContext != null)
        {
            singleton.appContext = WebApplicationContextUtils.getWebApplicationContext(singleton.servletContext);
        }
        
        if(singleton.appContext == null)
        {
            singleton.appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        }
        
        return singleton.appContext.getBean(beanName);
    }
}
